﻿using System;
using System.ComponentModel;
using ICSharpCode.SharpZipLib.Zip;

namespace ZipSpace
{
	public class ZipEntryView : INotifyPropertyChanged
	{
		private bool _isSelected;

		public ZipEntryView(ZipEntry zipEntry)
		{
			this.ZipEntry = zipEntry;

			int index = zipEntry.Name.IndexOf('/');
			if (index > -1)
				this.Path = zipEntry.Name.Substring(0, index);
			else
				this.Path = "";

			this.Extension = System.IO.Path.GetExtension(this.Name);

			this.CompressedSizeFormatted = FormatFileSize(zipEntry.CompressedSize);
			this.SizeFormatted = FormatFileSize(zipEntry.Size);

			if (zipEntry.Size > 0)
				this.CompressionRatio = 1F - ((float)zipEntry.CompressedSize / (float)zipEntry.Size);

			this.CompressionRatioFormatted = string.Format("{0:0%}", this.CompressionRatio.ToString("P2"));
		}

		public ZipEntry ZipEntry { get; private set; }

		public String Name
		{
			get
			{
				return this.ZipEntry.Name;
			}
		}

		public string Path { get; private set; }

		public string Extension { get; private set; }

		public bool IsSelected
		{
			get { return _isSelected; }
			set
			{
				_isSelected = value;
				RaisePropertyChanged("IsSelected");
			}
		}

		public long Size
		{
			get
			{
				return this.ZipEntry.Size;
			}
		}

		public long CompressedSize
		{
			get
			{
				return this.ZipEntry.CompressedSize;
			}
		}

		public String SizeFormatted { get; private set; }

		public String CompressedSizeFormatted { get; private set; }

		public float CompressionRatio { get; private set; }

		public string CompressionRatioFormatted { get; private set; }

		public static string FormatFileSize(long fileSize)
		{
			if (fileSize < 0)
				return fileSize.ToString();

			if (fileSize >= 1024 * 1024 * 1024)
				return string.Format("{0:########0.00} GB", ((double)fileSize) / (1024 * 1024 * 1024));
			else if (fileSize >= 1024 * 1024)
				return string.Format("{0:####0.00} MB", ((double)fileSize) / (1024 * 1024));
			else if (fileSize >= 1024)
				return string.Format("{0:####0.00} KB", ((double)fileSize) / 1024);
			else
				return string.Format("{0} bytes", fileSize);
		}

		public override string ToString()
		{
			return string.Format("{0}\n{1}", this.Name, this.CompressedSizeFormatted);
		}

		#region INotifyPropertyChanged values

		public event PropertyChangedEventHandler PropertyChanged;

		protected void RaisePropertyChanged(string propertyName)
		{
			var handler = PropertyChanged;
			if (handler != null)
			{
				handler(this, new PropertyChangedEventArgs(propertyName));
			}
		}

		#endregion

	}
}
